package ophiux.wechat.template.client;

import java.lang.reflect.Field;

import ophiux.OphiuxWechatTemplateMessageException;
import ophiux.wechat.template.base.Color;
import ophiux.wechat.template.base.TokenUtil;
import ophiux.wechat.template.base.Value;
import ophiux.wechat.template.request.BaseTemplate;
import ophiux.wechat.template.util.HttpUtil;
import ophiux.wechat.template.util.StringUtil;

public class WechatTemplateMessageParser implements IWechatTemplateMessageParser {

	@Override
	public String parse(BaseTemplate _request) throws OphiuxWechatTemplateMessageException {
		if(StringUtil.isEmpty(_request.getTOUSER())|| StringUtil.isEmpty(_request.getTEMPLATE_ID())){
			throw new OphiuxWechatTemplateMessageException("fail","Touser and Template_id is null");
		}
		
		String json="{\"touser\":\""+_request.getTOUSER()+"\",\"template_id\":\""+_request.getTEMPLATE_ID()+"\",\"url\":\""+_request.getURL()+"\",";
		json +="\"data\":{";
		Field[]  fieldList =  _request.getClass().getFields();
		try {
			for (int i = 0; i < fieldList.length; i++) {
				Field field=fieldList[i];
				Value value = field.getAnnotation(Value.class);
				Color color = field.getAnnotation(Color.class);
				if(StringUtil.isEmpty(value.value())){
					throw new OphiuxWechatTemplateMessageException("fail","@Value() is null");
				}
				json+="\""+value.value()+"\":{";
				json+="\"value\":\""+field.get(_request)+"\",";
				json+="\"color\":\""+(color.value()!=null?color.value():"")+"\"},";
			}
			json=json.substring(0,json.length()-1)+"}}";
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new OphiuxWechatTemplateMessageException(e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new OphiuxWechatTemplateMessageException(e);
		}
		System.out.println("请求json==="+json);
		
		return json;
	}
	
	@Override
	public String send(String appid,String secret,String json) throws OphiuxWechatTemplateMessageException{
		if(StringUtil.isEmpty(appid)||StringUtil.isEmpty(secret)||StringUtil.isEmpty(json)){
			throw new OphiuxWechatTemplateMessageException("fail","appid or secret or json is null");
		}
		
//		String access_token = HttpUtil.getAccessToken(appid, secret);
		String access_token = "";
		try {
			access_token = TokenUtil.getToken(appid, secret);
		} catch (Exception e) {
			throw new OphiuxWechatTemplateMessageException("fail","access_token get is exception");
		}
		System.out.println("获取accesstoken="+access_token);
		//{"errcode":0,"errmsg":"ok","msgid":59839785597976576}
		String result = HttpUtil.sendPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token,json);
		return result;
	}
	 
}
